require 'pathname'

Puppet::Type.newtype(:downloaded_package) do

  desc 'downloaded_package is used for installing software from archive file, like tar.gz, zip, etc. These files can be from internet, or from local storage.'

  ensurable

  newparam(:name, :namevar => true) do
    desc 'The name of the package.'
  end

  def self.supported_suffix
    ['.tar.gz', '.tar.xz', '.zip', '.tgz']
  end

  newparam(:source) do
    desc 'The location of archive file.'
    validate do |value|
      suffix_regex = ''
      resource.class.supported_suffix.each { |suf| suffix_regex += "#{suf.gsub(/\./,'\.')}|" }
      if value !~ /^(https?|file):\/\/.*(#{suffix_regex.chop})$/
        fail "Invalid source #{value}"
      end
    end
  end

  newparam(:install_dir) do
    desc 'Install directory for package, default value is "/opt".'
    validate do |value|
      fail("Invalid install_dir: #{install_dir}") unless Pathname.new(value).absolute?
    end
    defaultto '/opt'
  end

  newparam(:owner) do
    desc 'The owner of installed package.'
    newvalues(/[a-zA-Z0-9]+/)
    defaultto 'root'
  end

  validate do
    fail('source is required when ensure is present.') if self[:ensure] == :present and self[:source].nil?
  end

end
